package com.app.view;

import android.content.Context;
import android.graphics.PointF;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.utils.CommonUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import phone.qyg.com.qyg.R;


public class RollViewPager<T> extends ViewPager {

    @SuppressWarnings("unused")
    private String TAG = "RollViewPager";
    private Context context;
    private int currentItem;
    private List<? extends String> uriList; //现在改为url集合
    private ArrayList<View> dots;
    private TextView title;
    private ArrayList<String> titles;
    private int[] resImageIds;
    private int dot_focus_resId;
    private int dot_normal_resId;
    private OnPagerClickCallback onPagerClickCallback;
    private boolean isShowResImage = false;
    MyOnTouchListener myOnTouchListener;
    ViewPagerTask viewPagerTask;
    private PagerAdapter adapter;
    private boolean isAuto = true;//默认轮播是自动滑动

    PointF downP = new PointF();
    PointF curP = new PointF();
    private int abc = 1;
    private float mLastMotionX;
    private float mLastMotionY;
    private long start = 0;

    boolean isOpenInfinite; //开启无线左右循环
    int trueListSize;//集合真实大小

    public class MyOnTouchListener implements OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            curP.x = event.getX();
            curP.y = event.getY();
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    start = System.currentTimeMillis();
                    handler.removeCallbacksAndMessages(null);
                    downP.x = event.getX();
                    downP.y = event.getY();

                    break;
                case MotionEvent.ACTION_MOVE:
                    handler.removeCallbacks(viewPagerTask);
                    Log.i("d", (curP.x - downP.x) + "----" + (curP.y - downP.y));
                    break;
                case MotionEvent.ACTION_CANCEL:
                    startRoll(isAuto);
                    break;
                case MotionEvent.ACTION_UP:
                    downP.x = event.getX();
                    downP.y = event.getY();
                    long duration = System.currentTimeMillis() - start;
                    if (duration <= 500 && downP.x == curP.x) {
                        onPagerClickCallback.onPagerClick(currentItem);
                    } else {
                    }
                    startRoll(isAuto);
                    break;
            }
            return true;
        }
    }

    public boolean dispatchTouchEvent(MotionEvent ev) {
        final float x = ev.getX();
        final float y = ev.getY();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                getParent().requestDisallowInterceptTouchEvent(true);
                abc = 1;
                mLastMotionX = x;
                mLastMotionY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                if (abc == 1) {
                    if (Math.abs(x - mLastMotionX) < Math.abs(y - mLastMotionY)) {
                        abc = 0;
                        getParent().requestDisallowInterceptTouchEvent(false);
                    } else {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }

                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public class ViewPagerTask implements Runnable {
        @Override
        public void run() {
            currentItem = (currentItem + 1)
                    % (isShowResImage ? resImageIds.length : uriList.size());
            handler.obtainMessage().sendToTarget();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            RollViewPager.this.setCurrentItem(currentItem);
            startRoll(isAuto);
        }
    };

    public RollViewPager(Context context) {
        super(context);
    }

    public RollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 动态创建使用
     * @param context
     * @param dots
     * @param dot_focus_resId
     * @param dot_normal_resId
     * @param onPagerClickCallback
     */
    @SuppressWarnings("deprecation")
    public RollViewPager(Context context, ArrayList<View> dots,
                          int dot_focus_resId, int dot_normal_resId,
                            DisplayImageOptions options,
                          OnPagerClickCallback onPagerClickCallback) {
        super(context);
        setRollViewPege(context,dots,dot_focus_resId,dot_normal_resId,options,onPagerClickCallback);
    }

    /**
     * 设置相关信息
     * @param context
     * @param dots
     * @param dot_focus_resId
     * @param dot_normal_resId
     * @param onPagerClickCallback
     */
    public void setRollViewPege(Context context,ArrayList<View> dots,
                                int dot_focus_resId, int dot_normal_resId,
                                DisplayImageOptions options,
                                OnPagerClickCallback onPagerClickCallback){
        this.context = context;
        this.dots = dots;
        this.dot_focus_resId = dot_focus_resId;
        this.dot_normal_resId = dot_normal_resId;
        this.onPagerClickCallback = onPagerClickCallback;
        viewPagerTask = new ViewPagerTask();

        myOnTouchListener = new MyOnTouchListener();


        mDisplayImageOptions = options;
    }


    public void setUriList(List<String> uriList) {
        isShowResImage = false;
        this.uriList = uriList;
        if(isOpenInfinite){
            if(CommonUtil.isRequestList(uriList) && uriList.size() >1){
                trueListSize = uriList.size();
                String one = uriList.get(0);
                String end = uriList.get((trueListSize -1));
                uriList.add(0,end);
                uriList.add(one);
            }
        }
    }

    public List<String> getUriList(){
        return (List<String>) this.uriList;
    }


    /**
     * 现在只在首页使用 对其他也还没做处理 对 onPageSelected 处理不完整
     * @param isOpen
     */
    public void setOpenInfinite(boolean isOpen){
        isOpenInfinite = isOpen;
    }

    public void notifyDataChange() {
        adapter.notifyDataSetChanged();
    }

    public ArrayList<View> getDots() {
        return dots;
    }

    public void setDots(ArrayList<View> dots) {
        this.dots = dots;
    }

    public void setResImageIds(int[] resImageIds) {
        isShowResImage = true;
        this.resImageIds = resImageIds;
    }

    public void setTitle(TextView title, ArrayList<String> titles) {
        this.title = title;
        this.titles = titles;
        if (title != null && titles != null && titles.size() > 0)
            title.setText(titles.get(0));//
    }

    private boolean hasSetAdapter = false;
    private DisplayImageOptions mDisplayImageOptions;


    /**
     * 设置适配器 true 循环滑动 false 不滑动
     * @param isAutoState
     */
    @SuppressWarnings("deprecation")
    public void startRoll(boolean isAutoState) {
        isAuto = isAutoState;

        if (!hasSetAdapter) {
            hasSetAdapter = true;
            this.setOnPageChangeListener(new MyOnPageChangeListener());
            adapter = new ViewPagerAdapter();
            this.setAdapter(adapter);

            if(trueListSize >2){
                RollViewPager.this.setCurrentItem(1,false);
            }
        }
        if(isAutoState){
            handler.postDelayed(viewPagerTask, 5500);
        }

    }

    class MyOnPageChangeListener implements OnPageChangeListener {
        int oldPosition = 0;

        @Override
        public void onPageSelected(int position) {


            /**
             *  if ( imageViewList.size() > 1) { //多于1，才会循环跳转
             if ( position < 1) { //首位之前，跳转到末尾（N）
             position = 5;
             mViewPager.setCurrentItem(position,false);
             } else if ( position > 5) { //末位之后，跳转到首位（1）
             mViewPager.setCurrentItem(1,false); //false:不显示跳转过程的动画
             position = 1;
             }
             }
             */
            if(isOpenInfinite){
                if(position <1){
                    position = trueListSize;
                    RollViewPager.this.setCurrentItem(position,false);
                }else if(position >trueListSize){
                    RollViewPager.this.setCurrentItem(1,false); //false:不显示跳转过程的动画
                    position = 1;
                }
            }
            currentItem = position;
            if (title != null)
                title.setText(titles.get(position));
            if (dots != null && dots.size() > 0) {
//                dots.get(position).setBackgroundResource(dot_focus_resId);
//                dots.get(oldPosition).setBackgroundResource(dot_normal_resId);

                if(isOpenInfinite){
                    position = position-1;
                    int tempSize = trueListSize - 1;
                    if(position == 0 && oldPosition == 0){
                        oldPosition = trueListSize - 1;
                    }else if(position == tempSize && oldPosition == tempSize){
                        oldPosition = 0;
                        position = tempSize;
                    }
                }

                CommonUtil.setTextViewDrawableDirection((TextView) dots.get(position),4,dot_focus_resId);
                CommonUtil.setTextViewDrawableDirection((TextView) dots.get(oldPosition),4,dot_normal_resId);
            }
            oldPosition = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }
    }

    class ViewPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return isShowResImage ? resImageIds.length : uriList.size();
        }

        @Override
        public Object instantiateItem(View container, final int position) {
            View view = View.inflate(context, R.layout.viewpager_item, null);
            ((ViewPager) container).addView(view);
            view.setOnTouchListener(myOnTouchListener);
            ImageView imageView = (ImageView) view.findViewById(R.id.image);
            if (isShowResImage) {
                imageView.setImageResource(resImageIds[position]);
            } else {
                ImageLoader.getInstance().displayImage(uriList.get(position), imageView, mDisplayImageOptions);
            }
            return view;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView((View) arg2);
        }

        @Override
        public void finishUpdate(View arg0) {
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }

    }

    @Override
    protected void onDetachedFromWindow() {
        handler.removeCallbacksAndMessages(null);
        super.onDetachedFromWindow();
    }

    public interface OnPagerClickCallback {
        public abstract void onPagerClick(int position);
    }

}
